/*
 * GYBuffer.cpp
 *
 *  Created on: 2015-9-25
 *      Author: gy
 */

#ifndef GYBUFFER_CPP_
#define GYBUFFER_CPP_


#include "CTBase.h"

#include "GYBuffer.h"

GYBuffer::GYBuffer():m_iPos(0), m_pszBuf(0), m_iSize(0), m_iAct(0), m_bNew(false)
{

}

GYBuffer::GYBuffer(const GYBuffer &buf):m_iPos(0), m_pszBuf(0), m_iSize(0), m_iAct(0), m_bNew(false)
{
	Copy(buf);
}

void GYBuffer::Copy(const GYBuffer &buf)
{
	if (this == &buf)
	{
		return;
	}

	Detach();

	if (buf.m_bNew)
	{
		CT_ASSERT(buf.m_pszBuf && buf.m_iSize > 0);
		Attach(NULL, buf.m_iSize, buf.m_iAct);
		memcpy(m_pszBuf, buf.m_pszBuf, m_iSize);
		m_iPos = buf.m_iPos;
	}
	else
	{
		if (buf.m_pszBuf != NULL && buf.m_iSize > 0)
		{
			Attach(buf.m_pszBuf, buf.m_iSize, buf.m_iAct);
			Append(buf.m_iPos);
		}
	}
}

GYBuffer::~GYBuffer()
{
    Detach();
}

GYBuffer &GYBuffer::operator=(const GYBuffer &buff)
{
	Copy(buff);
	return *this;
}

int GYBuffer::Attach(char* pszBuf, int iSize, int iAct)
{
	if (iSize <= 0)
	{
		return -1;
	}

    Detach();

    if (pszBuf == NULL)
    {
        m_bNew = true;
        m_pszBuf = new char[iSize];
        if (m_pszBuf == NULL)
        {
            return -1;
        }
    }
    else
    {
        m_bNew = false;
        m_pszBuf = pszBuf;
    }

    m_iSize = iSize;
    m_iPos = 0;
    m_iAct = iAct;

    return 0;
}

void GYBuffer::Detach()
{
    if (m_pszBuf != NULL && m_bNew)
    {
        delete [] m_pszBuf;
    }

    m_pszBuf = 0;
    m_iSize = 0;
    m_iPos = 0;
    m_iAct = 0;
    m_bNew = false;
}

int GYBuffer::Append(const char* pszBuf, int iLen)
{
    CT_ASSERT(pszBuf && iLen >= 0);

    if (iLen > GetFreeLen())   //org: if (iLen >= GetFreeLen()), modified by will 2008-10-17
    {
        return -1;
    }

    memcpy(m_pszBuf + m_iPos, pszBuf, iLen);
    m_iPos += iLen;
    return 0;
}

int GYBuffer::Append(int iLen)
{
    CT_ASSERT(iLen >= 0);

    if (iLen > GetFreeLen())  //org: if (iLen >= GetFreeLen()), modified by will 2008-10-17
    {
        return -1;
    }

    m_iPos += iLen;
    return 0;
}

int GYBuffer::RemoveHead(int iLen)
{
    if (iLen > m_iPos)
    {
        return -1;
    }
    else if (iLen < m_iPos) // 优化
    {
        memmove(m_pszBuf, m_pszBuf + iLen, m_iPos - iLen);
    }

    m_iPos -= iLen;
    return 0;
}

int GYBuffer::RemoveTail(int iLen)
{
    if (iLen > m_iPos)
    {
        return -1;
    }

    m_iPos -= iLen;
    return 0;
}

int GYBuffer::Clear()
{
    m_iPos = 0;
    return 0;
}
















#endif /* GYBUFFER_CPP_ */
